# -*- coding:utf-8 -*-
# @Time: 2020/9/8 9:57
# @Author: gupeng
# @File: shorty_url.py
# @Desc: 短网址--hset,hget测试

from base36 import dumps

ID_COUNTER = 'ShortyUrl::id_counter'
URL_HASH = 'ShortyUrl::url_hash'


class ShortyUrl:
    def __init__(self, client):
        self.client = client

    def shorten(self, target_url):
        """
        为目标网址创建并存储响应得短网址ID
        :param target_url: 目标网址
        :return: 短网址id
        """
        new_id = self.client.incrby(ID_COUNTER)
        short_id = dumps(new_id)
        self.client.hset(URL_HASH, short_id, target_url)
        return short_id

    def restore(self, short_id):
        """
        根据给定得短网址ID，返回一直对应的目标网址
        :param short_id: 短网址ID
        :return: 目标网址
        """
        return self.client.hget(URL_HASH, short_id)
